package com.hhf.ftp.service.impl;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service("ftps")
public class FtpsServiceImpl extends FtpServiceImpl {

    private void getClient(String username, String password, String ip, Integer port) throws IOException {
        if(port == null) {
            port = 21;
        }
        FTPSClient ftpClient = new FTPSClient(false);
        ftpClient.setDataTimeout(60000);
        ftpClient.connect(ip, port);// 连接FTP服务器
        int reply = ftpClient.getReplyCode();
        if(FTPReply.isPositiveCompletion(reply)){
            if(ftpClient.login(username, password)){
                ftpClient.execPBSZ(0);
                ftpClient.execPROT("P");
                ftpClient.enterLocalPassiveMode();
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.setRemoteVerificationEnabled(false);
            }
        }
        super.client = ftpClient;
    }

    @Override
    public String connection(String username, String password, String ip, Integer port) throws IOException {
        getClient(username, password, ip, port);
        return "FTPS connection success!";
    }
}
